package com.cqgc.controller;

import com.cqgc.pojo.dto.RoleDTO.RoleAddDTO;
import com.cqgc.pojo.dto.RoleDTO.RoleUpdateDTO;
import com.cqgc.pojo.dto.RoleDTO.RoleParm;
import com.cqgc.pojo.dto.RoleDTO.SelectType;
import com.cqgc.pojo.entity.PageResult;
import com.cqgc.pojo.entity.Result;
import com.cqgc.pojo.entity.Role;
import com.cqgc.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/role")
@Api(tags = "角色接口")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @ApiOperation("查询")
    @GetMapping("/list")
    public Result<PageResult> list( RoleParm roleParm)
    {
        PageResult pageResult = roleService.list(roleParm);
        if (pageResult != null){
            return Result.success(new PageResult(pageResult.getTotal(),pageResult.getRecords()));
        }
        return Result.error();
    }
    @PostMapping
    @ApiOperation("新增角色")
    @RequiresRoles("admin")
    public Result add(@RequestBody RoleAddDTO roleDTO) {
        Role one = roleService.getOneAdd(roleDTO);
        if (one != null){
            return Result.error("该角色已存在!");
        }
        if (roleService.addRole(roleDTO)) {
            return Result.success("新增角色成功!");
        }
        return Result.error("新增角色失败!");
    }

    //编辑
    @PutMapping
    @ApiOperation("编辑角色")
    @RequiresRoles("admin")
    public Result edit(@RequestBody RoleUpdateDTO Role) {
        if (roleService.updateRole(Role)) {
            return Result.success("编辑角色成功!");
        }
        return Result.error("编辑角色失败!");
    }

    //删除
    @ApiOperation("删除角色")
    @DeleteMapping("/{rid}")
    @RequiresRoles("admin")
    public Result delete(@PathVariable("rid") int rid) {
        if (roleService.removeById(rid)) {
            return Result.success("删除角色成功!");
        }
        return Result.error("删除角色失败!");
    }

    //获取角色下拉数据
    @ApiOperation("获取角色下拉数据")
    @GetMapping("/getListSelect")
    public Result getListSelect() {
        List<Role> list = roleService.list();
        ArrayList<SelectType> roleList = new ArrayList<>();
        Optional.ofNullable(list).orElse(new ArrayList<>())
                .stream().forEach(item->{
                    SelectType selectType = new SelectType();
                    selectType.setValue(item.getRid());
                    selectType.setLabel(item.getRealName());
                    roleList.add(selectType);
                });
        return Result.success("查询成功",roleList);
    }

}
